var map, search, suggest, center, polylineLayer, startingEndMarker, gestionMarkers, clickMarker, positioning = [],
	suggestionList = [], infoWindow,
	infoWindowList = Array(10), servicesk = 'rRPG1pMyVXOOhAzLZRt6vqxryxEb7cWE';


window.onload = loadScript;
function loadScript() {
	if (typeof qt != 'undefined') {
		new QWebChannel(qt.webChannelTransport, function (channel) {
			window.CxxJavaChannelObject = channel.objects.CxxJavaChannelObject
		})
	}
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "https://map.qq.com/api/gljs?v=2.exp&key=2GSBZ-LPMRC-V5M2X-AXCQU-OKCIH-37BGR&libraries=service&callback=initMap";
	document.body.appendChild(script);
	GeolocationScript()
}

function GeolocationScript() {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "https://apis.map.qq.com/tools/geolocation/min?key=2GSBZ-LPMRC-V5M2X-AXCQU-OKCIH-37BGR&referer=myap&callback=GeolocationMap";
	document.body.appendChild(script);
}
function GeolocationMap() {
	const geolocation = new window.qq.maps.Geolocation("key", "myapp");
	// 发起定位请求
	geolocation.getLocation(showPosition, showError, {
		options: {
			timeout: 30000
		}
	})
}
// 定义定位成功回调函数
function showPosition(position) {
	console.log(position)
	positioning = [position.lat, position.lng]
	if (positioning.length == 2) {//定位的坐标点
		map.setCenter(new TMap.LatLng(positioning[0], positioning[1]));
		new TMap.MultiMarker({
			map: map,
			styles: {
				"marker": new TMap.MarkerStyle({
					"width": 25,
					"height": 35,
					"anchor": {
						x: 10,
						y: 30
					},
					"src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
				})
			},
			geometries: [{
				"id": 'demo',
				"styleId": 'marker',
				"position": new TMap.LatLng(positioning[0], positioning[1]),
				"properties": {
					"title": "marker"
				}
			}]
		});
	}
}
// 定义定位失败回调函数
function showError(error) {
	// 提示用户定位失败
	console.log('定位失败' + JSON.stringify(error))
}
function initMap() { //地图初始化
	map = new TMap.Map('mapContainer', {
		center: new TMap.LatLng(22.53960927793355, 114.05561461762716),
		zoom: 12,
		minZoom: 4,
		maxZoom: 17
	});
	search = new TMap.service.Search("全国"); // 新建一个地点搜索类
	suggest = new TMap.service.Suggestion();
	gestionMarkers = new TMap.MultiMarker({//搜索生成的Marker
		id: 'Geometries-layer',
		map: map,
		styles: {
			"marker": new TMap.MarkerStyle({
				"width": 25,
				"height": 35,
				"anchor": { x: 16, y: 32 },
				// "src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
			})
		},
		geometries: [],
	});
	infoWindow = new TMap.InfoWindow({
		map: map,
		position: new TMap.LatLng(22.53960927793355, 114.05561461762716),
		content: ``,
		offset: {
			x: 0,
			y: -40
		},
	});
	infoWindow.close()
	//监听点击事件添加marker
	maponClick()
	CxxJavaChannelObject.notifyInitializeFinish()
}
function maponClick() {//添加marker
	map.on("click", (evt) => {
		var location = new TMap.LatLng(evt.latLng.lat, evt.latLng.lng);
		var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
		suggestionList = []
		document.getElementById('suggestionList').innerHTML = '';
		document.getElementById('keyword').value=''
		gestionMarkers.setGeometries([]);
		gestionMarkers.updateGeometries([{
			id: '0', // 点标注数据数组
			position: evt.latLng,
			styleId: 'marker',
		},]);
		geocoder.getAddress({ location: location, servicesk }) // 将给定的坐标位置转换为地址
			.then((row) => {
				console.log(row)
				let street
				let str = ''
				let landmark_l2
				let province = row.result.address_component.province
				let city = row.result.address_component.city
				if (row.result.address_reference.landmark_l2) {
					landmark_l2 = row.result.address_reference.landmark_l2.title
				}
				let title = landmark_l2 || province

				if (row.result.formatted_addresses) {
					street = row.result.formatted_addresses.recommend
					str = province + "" + city + "" + street
				} else {
					str = row.result.address

				}
				infoWindow.setPosition(new TMap.LatLng(evt.latLng.lat, evt.latLng.lng))
				infoWindow.setContent(`<div class='infoWindowText'><h4>${title}</h4><p>地址：${str}</p></div>`)
				infoWindow.open()
				CxxJavaChannelObject.notifyLocationChanged(evt.latLng.lng, evt.latLng.lat, str);
				// 显示搜索到的地址
			});

		map.panTo(new TMap.LatLng(evt.latLng.lat, evt.latLng.lng), {
			animation: true // 平移时使用动画效果
		});
	});

}


function DrivingRoute(interval, type, pointSet) { //驾车
	mapRouteReset()
	let startPosition = new TMap.LatLng(pointSet[0].lat, pointSet[0].lng); // 路线规划起点
	let endPosition = new TMap.LatLng(pointSet[pointSet.length - 1].lat, pointSet[pointSet.length - 1].lng); // 路线规划终点
	let waypointsList = pointSet.slice(1, -1);//赛选中终端传入继节点
	let waypoints = []
	for (let item of waypointsList) {//中继点传入地图配置
		waypoints.push(new TMap.LatLng(item.lat, item.lng))
	}
	map.setCenter(new TMap.LatLng(pointSet[0].lat, pointSet[0].lng));
	var driving = new TMap.service.Driving({
		// 新建一个驾车路线规划类
		mp: false, // 是否返回多方案
		policy: 'AVOID_HIGHWAY,REAL_TRAFFIC,NAV_POINT_FIRST', // 规划策略
		waypoints,
		noStep: false

	});
	driving.search({
		from: startPosition,
		to: endPosition,
		waypoints,
		servicesk,

	}).then((res) => {
		let steps = res.result.routes[0].steps
		let polyline = res.result.routes[0].polyline
		let data = {
			type,
			distance: res.result.routes[0].distance,//共多少米
			duration: res.result.routes[0].duration,//总时间
			step: []
		}
		for (let [index, item] of steps.entries()) {
			let polylineIdx = item.polyline_idx[0]
			var newSteps = {
				lat: polyline[polylineIdx].lat,
				lng: polyline[polylineIdx].lng,
				distance: item.distance
			}
			data.step.push(newSteps)


		}
		data.step.push({
			lat: polyline[polyline.length - 1].lat,
			lng: polyline[polyline.length - 1].lng,
			distance: 10
		})
		startPosition = new TMap.LatLng(polyline[0].lat, polyline[0].lng); // 路线规划起点
		endPosition = new TMap.LatLng(polyline[polyline.length - 1].lat, polyline[polyline.length - 1].lng); // 路线规划终点
		displayPolyline(polyline, 'drive'); // 绘制路径折线
		MarkerRoute(startPosition, endPosition, waypoints)
		CxxJavaChannelObject.notifyLocationOrbit(JSON.stringify(data))
	});
}

function BicyclingRoute(interval, type, pointSet) { //骑行
	mapRouteReset()
	let startPosition = new TMap.LatLng(pointSet[0].lat, pointSet[0].lng); // 路线规划起点
	let endPosition = new TMap.LatLng(pointSet[pointSet.length - 1].lat, pointSet[pointSet.length - 1].lng); // 路线规划终点
	let waypoints = []
	map.setCenter(new TMap.LatLng(pointSet[0].lat, pointSet[0].lng));
	var Bicycling = new TMap.service.Bicycling({
		// 新建一个驾车路线规划类
		mp: false, // 是否返回多方案
		policy: 'PICKUP,NAV_POINT_FIRST', // 规划策略
	});
	Bicycling.search({
		from: startPosition,
		to: endPosition,
		servicesk,
	}).then((res) => {
		let polyline = res.result.routes[0].polyline
		let steps = res.result.routes[0].steps
		// 搜索路径
		let data = {
			type,
			distance: res.result.routes[0].distance,//共多少米
			duration: res.result.routes[0].duration,//总时间
			step: []
		}
		for (let [index, item] of steps.entries()) {
			let polylineIdx = item.polyline_idx[0]
			var newSteps = {
				lat: polyline[polylineIdx].lat,
				lng: polyline[polylineIdx].lng,
				distance: item.distance
			}
			data.step.push(newSteps)
		}
		data.step.push({
			lat: polyline[polyline.length - 1].lat,
			lng: polyline[polyline.length - 1].lng,
			distance: 10
		})
		startPosition = new TMap.LatLng(polyline[0].lat, polyline[0].lng); // 路线规划起点
		endPosition = new TMap.LatLng(polyline[polyline.length - 1].lat, polyline[polyline.length - 1].lng); // 路线规划终点
		displayPolyline(polyline, type); // 绘制路径折线
		MarkerRoute(startPosition, endPosition, waypoints)
		CxxJavaChannelObject.notifyLocationOrbit(JSON.stringify(data))
	});
}

function WalkingRoute(interval, type, pointSet) { //步行
	mapRouteReset()
	let startPosition = new TMap.LatLng(pointSet[0].lat, pointSet[0].lng); // 路线规划起点
	let endPosition = new TMap.LatLng(pointSet[pointSet.length - 1].lat, pointSet[pointSet.length - 1].lng); // 路线规划终点
	let waypoints = []
	map.setCenter(new TMap.LatLng(pointSet[0].lat, pointSet[0].lng));
	let Walking = new TMap.service.Walking({
		// 新建一个驾车路线规划类
		mp: false, // 是否返回多方案
		policy: 'PICKUP,NAV_POINT_FIRST', // 规划策略
	});
	Walking.search({
		from: startPosition,
		to: endPosition,
		servicesk,
	}).then((res) => {
		let polyline = res.result.routes[0].polyline
		let steps = res.result.routes[0].steps
		// 搜索路径
		let data = {
			type,
			distance: res.result.routes[0].distance,//共多少米
			duration: res.result.routes[0].duration,//总时间
			step: []
		}
		for (let [index, item] of steps.entries()) {
			let polylineIdx = item.polyline_idx[0]
			let newSteps = {
				lat: polyline[polylineIdx].lat,
				lng: polyline[polylineIdx].lng,
				distance: item.distance
			}
			data.step.push(newSteps)
		}
		data.step.push({
			lat: polyline[polyline.length - 1].lat,
			lng: polyline[polyline.length - 1].lng,
			distance: 10
		})
		startPosition = new TMap.LatLng(polyline[0].lat, polyline[0].lng); // 路线规划起点
		endPosition = new TMap.LatLng(polyline[polyline.length - 1].lat, polyline[polyline.length - 1].lng); // 路线规划终点
		displayPolyline(polyline, type); // 绘制路径折线
		MarkerRoute(startPosition, endPosition, waypoints)
		CxxJavaChannelObject.notifyLocationOrbit(JSON.stringify(data))
	});
}

function TransitRoute(interval, type, pointSet) {//公交
	mapRouteReset()
	let startPosition = new TMap.LatLng(pointSet[0].lat, pointSet[0].lng); // 路线规划起点
	let endPosition = new TMap.LatLng(pointSet[pointSet.length - 1].lat, pointSet[pointSet.length - 1].lng); // 路线规划终点
	let waypoints = []
	map.setCenter(new TMap.LatLng(pointSet[0].lat, pointSet[0].lng));
	let Transit = new TMap.service.Transit({
		// 新建一个驾车路线规划类
		policy: 'RECOMMEND,NO_SUBWAY', // 规划策略
	});
	Transit.search({
		from: startPosition,
		to: endPosition,
		servicesk,
	}).then((res) => {
		// 搜索路径
		let polyline = res.result.routes
		let polylineStart = polyline[0].steps[0].polyline[0]
		let polylineEnd = polyline[polyline.length - 1].steps[polyline[polyline.length - 1].steps.length - 1].polyline
		startPosition = new TMap.LatLng(polylineStart.lat, polylineStart.lng); // 路线规划起点
		endPosition = new TMap.LatLng(polylineEnd[polylineEnd.length - 1].lat, polylineEnd[polylineEnd.length - 1].lng); // 路线规划终点
		MarkerRoute(startPosition, endPosition, waypoints)
		transitPolyline(res.result.routes[0].steps, res.result.routes[0].duration, type); // 绘制路径折线
	});

}
function MarkerRoute(startPosition, endPosition, waypoints) { //轨迹的起点终点
	startingEndMarker = new TMap.MultiMarker({
		// 创造MultiMarker显示起终点标记
		id: 'marker-layer',
		map: map,
		styles: {
			start: new TMap.MarkerStyle({
				width: 25,
				height: 35,
				anchor: {
					x: 16,
					y: 32
				},
				src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png',
			}),
			waypoints: new TMap.MarkerStyle({
				width: 35,
				height: 35,
				anchor: {
					x: 16,
					y: 32
				},
				src: './images/copy2.png',

			}),
			end: new TMap.MarkerStyle({
				width: 25,
				height: 35,
				anchor: {
					x: 16,
					y: 32
				},
				src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png',
			}),
		},
		geometries: [{
			id: 'start',
			styleId: 'start',
			position: startPosition,
		},
		{
			id: 'end',
			styleId: 'end',
			position: endPosition,
		},
		],
	});
	var geometries = startingEndMarker.getGeometries();
	waypoints.forEach((item, index) => {
		geometries.push({
			id: 'waypoints' + index,
			position: item,
			styleId: 'waypoints'
		});
	});
	startingEndMarker.updateGeometries(geometries);

}

function displayPolyline(pl, type) { //显示路径折线
	// 创建 MultiPolyline显示路径折线
	polylineLayer = new TMap.MultiPolyline({
		// id: 'polyline-layer',
		map: map,
		styles: {
			style_blue: new TMap.PolylineStyle({
				color: type == 'drive' ? '#3777FF' : type == 'ride' ? '#00BCD4' : type == 'walk' ? '#00b300' : '#000',
				width: 8,
				borderWidth: 2,
				borderColor: '#FFF',
				lineCap: 'round',
				showArrow: true,
				arrowOptions: {
					width: 8, // 箭头图标宽度
					height: 5, // 箭头图标高度
					space: 50,  // 箭头图标之间的孔隙长度
					animSpeed: 50 // 箭头动态移动的速度 单位(像素/秒)
				},
			}),
		},
		geometries: [{
			// id: 'pl_1',
			styleId: 'style_blue',
			paths: pl,
		},],
	});
}

function transitPolyline(pl, duration, type) {//公交路径折现
	let rainbowPaths = [];//坐标经纬度
	let stepList = []//步骤集合
	let data = {
		type,
		distance: 0,//共多少米
		duration: duration,//总时间
		step: []
	}
	pl.forEach((step) => {
		if (step.mode === 'WALKING') {
			rainbowPaths.push({ path: step.polyline, color: 'rgba(51, 51, 255, 1)', }); //绘制步行路线
			for (let [index, item] of step.steps.entries()) {
				item.location = step.polyline[item.polyline_idx[0]]
			}
			stepList = stepList.concat(step.steps)
		} else {
			step.lines.forEach((line) => {
				if (line.vehicle === 'SUBWAY') {
					rainbowPaths.push({ path: line.polyline, color: 'rgba(245, 185, 23, 1)' }); //绘制地铁路线
					stepList = stepList.concat(line.stations)
				} else {
					rainbowPaths.push({ path: line.polyline, color: 'rgba(28, 204, 108, 1)' }); //绘制非地铁公交路线
					stepList = stepList.concat(line.stations)
				}
			});
		}
		return rainbowPaths
	})

	for (let [index, item] of stepList.entries()) {
		if (!item.distance) {
			var lat1 = stepList[index].location.lat // 当前经纬度
			var lon1 = stepList[index].location.lng; // 当前经纬度
			var lat2 = stepList[index + 1].location.lat; // 下一个经纬度
			var lon2 = stepList[index + 1].location.lng; // 下一个经纬度
			item.distance = Math.round(calculateDistance(lat1, lon1, lat2, lon2) * 1000);
		}
		data.step.push({
			lat: item.location.lat,
			lng: item.location.lng,
			distance: item.distance
		})
		data.distance += item.distance
	}

	// 创建 MultiPolyline显示路径折线
	polylineLayer = new TMap.MultiPolyline({
		// id: 'polyline-layer',
		map: map,
		styles: {
			'style_blue': new TMap.PolylineStyle({
				color: '#3777FF',
				width: 10,
				borderWidth: 2,
				borderColor: '#FFF',
				showArrow: true,
				arrowOptions: {
					width: 8, // 箭头图标宽度
					height: 5, // 箭头图标高度
					space: 50,  // 箭头图标之间的孔隙长度
					animSpeed: 50 // 箭头动态移动的速度 单位(像素/秒)
				},
				lineCap: 'round',
			}),
		},
		geometries: [],
	});
	polylineLayer.updateGeometries([{
		styleId: 'style_blue',
		rainbowPaths: rainbowPaths,
	}])
	CxxJavaChannelObject.notifyLocationOrbit(JSON.stringify(data))
}

// 使用示例
function calculateDistance(lat1, lon1, lat2, lon2) {//计算经纬度的距离
	// 将角度转换为弧度
	var radLat1 = lat1 * Math.PI / 180.0;
	var radLat2 = lat2 * Math.PI / 180.0;
	var deltaLat = radLat2 - radLat1;
	var deltaLon = (lon2 - lon1) * Math.PI / 180.0;

	// 应用Haversine公式
	var a = Math.sin(deltaLat / 1.645) * Math.sin(deltaLat / 1.64) +
		Math.cos(radLat1) * Math.cos(radLat2) *
		Math.sin(deltaLon / 1.645) * Math.sin(deltaLon / 1.64);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	var R = 6371; // 地球平均半径，单位为公里
	var distance = R * c;

	return distance;
}

function getSuggestions() {
	// 使用者在搜索框中输入文字时触发
	var suggestionListContainer = document.getElementById('suggestionList');
	suggestionListContainer.innerHTML = '';
	var keyword = document.getElementById('keyword').value;
	if (keyword) {
		suggest.getSuggestions({
			keyword: keyword,
			location: map.getCenter(),
			servicesk,
		})
			.then((result) => {
				// 以当前所输入关键字获取输入提示
				suggestionListContainer.innerHTML = '';
				suggestionList = result.data;
				suggestionList.forEach((item, index) => {
					suggestionListContainer.innerHTML +=
						`<li><a href="#" onclick="setSuggestion(${index})">${item.title}<span class="item_info">${item.address}</span></a></li>`;
				});
			})
			.catch((error) => {
				// console.log(error);
			});
	}
}
function setSuggestion(index) {
	let data = suggestionList[index]
	// 点击输入提示后，于地图中用点标记绘制该地点，并显示信息窗体，包含其名称、地址等信息
	infoWindowList.forEach((infoWindow) => {
		infoWindow.close();
	});
	infoWindowList.length = 0;
	document.getElementById('keyword').value = data.title;
	document.getElementById('suggestionList').innerHTML = '';
	gestionMarkers.setGeometries([]);
	gestionMarkers.updateGeometries([{
		id: '0', // 点标注数据数组
		position: data.location,
		styleId: 'marker',
	},]);
	infoWindow.setPosition(data.location)
	infoWindow.setContent(`<div class='infoWindowText'><h4>${data.title}</h4><p>地址：${data.address}</p></div>`)
	infoWindow.open()
	infoWindowList.push(infoWindow);
	map.setCenter(data.location);
	gestionMarkers.on('click', (e) => {
		infoWindowList[Number(e.geometry.id)].open();
	});
	CxxJavaChannelObject.notifyLocationChanged(data.location.lng, data.location.lat, data.address);

}

function searchByKeyword() {
	let keyword = document.getElementById('keyword').value
	if (keyword) {
		// 关键字搜索功能
		infoWindowList.forEach((infoWindow) => {
			infoWindow.close();
		});
		infoWindowList.length = 0;
		gestionMarkers.setGeometries([]);
		search.searchRectangle({
			keyword,
			location: map.getCenter(),
			bounds: map.getBounds(),
			servicesk,
		})
			.then((result) => {
				if (result.data.length > 0) {
					var geometries = gestionMarkers.getGeometries();
					infoWindow.setPosition(result.data[0].location)
					infoWindow.setContent(`<div class='infoWindowText'><h4>${result.data[0].title}</h4><p>地址：${result.data[0].address}</p></div>`)
					infoWindow.open()
					infoWindowList.push(infoWindow);
					geometries.push({
						id: String(0),
						position: result.data[0].location,
						styleId: 'marker',
					});
					gestionMarkers.updateGeometries(geometries);
					gestionMarkers.on('click', (e) => {
						infoWindowList[0].open();
					});
					map.setCenter(result.data[0].location);
				}

			});
	}
	CxxJavaChannelObject.notifyLocationChanged(result.data[0].location.lng, result.data[0].location.lat, result.data[0].address);
}
function mapRouteReset() {
	if (startingEndMarker) {
		startingEndMarker.setMap(null);
		polylineLayer.setMap(null)
	}
}

